// pages/navigator/filterDetail/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    orderName: '',
    orderId: '',
    customerName:'',
    completionRate:'',
    state:'',
    remark: '',
    processArry:[],
    showAuthPopup2:false,
    currentWorkerId:'',
    currentNumber:'',
    listFlag:false,
    currentOrderProcessId:'',
    currentOrderWorkerId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id:options.id
    })
    this.init(options.id)
  },
  init(id){
    try {
      this.loadFormData(id).then((res) => {
        console.log(9998,res)
        this.setData({
          completionRate: res.completionRate,
          orderName: res.orderName,
          orderId: res.orderId,
          customerName: res.customerName,
          state:res.state,
          remark: res.remark,
          processArry:res.processArry
        })
      });
      
      
    } catch (error) {
      // 错误处理
    }
  },
  async loadFormData(id) {
    try {
      // 1. 获取订单基础数据
      const orderResult = await this.wxRequest({
        url: app.globalData.onlineUrl+'/getOrderByIdMini',
        method: 'POST',
        data: { id: id }
      });
      const formData = {
        ...orderResult,
        processArry: []
      };
      console.log(123456,formData);
      // 2. 获取工序数据
      const processResult = await this.wxRequest({
        url: app.globalData.onlineUrl+'/getProcessByProcessIds',
        method: 'POST',
        data: { orderId:formData.orderId }
      });
      
      // 3. 获取每个工序的工人数据
      const processPromises = processResult.map(async process => {
        const workerResult = await this.wxRequest({
          url: app.globalData.onlineUrl+'/getWorkerByWorkerIds',
          method: 'POST',
          data: { orderProcessId:process.orderProcessId }
        });
        return {
          ...process,
          workers: workerResult
        };
      });
      // 4. 等待所有工序数据加载完成
      const processedData = await Promise.all(processPromises);
      formData.processArry = processedData;
      console.log('表单数据加载完成:', formData);
      return formData;
    } catch (error) {
      console.error('数据加载失败:', error);
      throw error;
    }
  },
// 微信小程序请求封装（示例）
wxRequest: function (options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code ==1) {
          resolve(res.data.data);
        } else {
          reject(new Error(`请求失败: ${res.data.code}`));
        }
      },
      fail: (err) => {
        reject(new Error('网络请求失败'));
      }
    });
  })
},
updateWorker(e){
  console.log(e.currentTarget.dataset.type);
  this.setData({
    currentNumber:e.currentTarget.dataset.type,
    currentWorkerId:e.currentTarget.dataset.id,
    showAuthPopup2:true
  })
},
currentNumberInput(e){
  let value = e.detail.value;
  this.data.currentNumber=value
  this.setData({
    currentNumber:this.data.currentNumber
 })
},
onClosePopup2() {
  this.setData({ showAuthPopup2: false });
},
showList(e){
  this.setData({
    currentOrderProcessId:e.currentTarget.dataset.name,
    currentOrderWorkerId:e.currentTarget.dataset.id,
    listFlag:true
  })
  this.selctWorkerList()
},
onClosePopup3(){
  this.setData({ listFlag: false });
},
selctWorkerList(){
  let _this=this;
      wx.request({
        url: app.globalData.onlineUrl+'/selctWorkerList',
        method: 'POST',
        data: {
          orderId:_this.data.orderId,
          processId:_this.data.currentOrderProcessId,
          workerId:_this.data.currentOrderWorkerId,
        },
        header: {'content-type': 'application/json' }, // 请求头
        success: function (res) {
          _this.setData({ listData: res.data.data });
        },
        fail: function (err) {
        }
      }); 
},
updateWorkerNum(){
  if(!/^[0-9]+$/.test(String(this.data.currentNumber))){
    wx.showToast({
      title: '请输入正确的数字格式',
      icon: 'none'
    });
    return
  }
  let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/updateWorkerNum',
          method: 'POST',
          data: {
            number:_this.data.currentNumber,
            id:_this.data.currentWorkerId
          },
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            wx.showToast({
              title: '操作成功',
              icon: 'success'
            });
            _this.setData({ showAuthPopup2: false });
            _this.init(_this.data.id);
          },
          fail: function (err) {
          }
        }); 
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})